﻿
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace FaceDectionSiliverlight
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            Loaded += MainPage_Loaded;
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            _captureSource = new CaptureSource();
            _captureSource.VideoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();
            _captureSource.CaptureImageCompleted += new EventHandler<CaptureImageCompletedEventArgs>(captureCompleted);

            //_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            _socketConnection = new SocketConnection("127.0.0.1", 4502);
            _socketConnection.MessageReceived += _socketConnection_MessageReceived;

            InitCaptureStoryborad();
            InitActornStoryborad();
            
        }

        void _socketConnection_MessageReceived(object sender, MessageEventArgs e)
        {
            _veryCount++;
            bool result = false;
            if (e.Message.IndexOf("#") > -1)
            {
                this.Dispatcher.BeginInvoke(new Action(() =>
                {
                    MessageBox.Show("没有检测到人脸");
                }));
            }
            else
            {
               
                try
                {
                    var detecteResult = Newtonsoft.Json.JsonConvert.DeserializeObject<QSFacePointsModel>(e.Message);
                    result = AntiFaceHelper.Verity(detecteResult.pitch, detecteResult.roll, detecteResult.yaw, detecteResult.points,_currentActon);
                    
                }
                catch
                {

                }
                
            }
            //int index=_veryCount-1;
            //_veryCountResult[index] = result;
            if (result)
            {
                if (_veryCount == VERYCOUNT)
                {

                    this.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        MessageBox.Show("验证成功");
                    }));
                }

                if (_veryCount != VERYCOUNT)
                {
                    this.Dispatcher.BeginInvoke(new Action(() => { _actionStoryborad.Begin(); }));
                    
                }
                
            }
            else
            {

                this.Dispatcher.BeginInvoke(new Action(() =>
                {
                    MessageBox.Show("验证失败");
                }));
            }
            
            //else
            //{
            //    _veryCount = 0;
            //    _captureCount = TIMESPAN_ACTION + 1;
            //}
            

        }

        #region 变量

        /// <summary>
        /// 倒计时时间秒
        /// </summary>
        const int TIMESPAN_COUNT = 3;

        /// <summary>
        /// 连续认证的次数
        /// </summary>
        const int VERYCOUNT = 3;

        protected CaptureSource _captureSource;

        protected SocketConnection _socketConnection;

        const string MSGENDSIGN = "**";

        protected int _currentRandow = 0;

        private Random _random = new Random(DateTime.Now.Second);

        Storyboard _captureStoryborad = null;

        private Storyboard _actionStoryborad = null;

        ImageBrush _captureImage;

        private int _timeCount = TIMESPAN_COUNT+1;

        private int _veryCount = 0;

        private AntiFaceAction _currentActon = AntiFaceAction.UnKnown;


        #endregion
         
        #region 受保护函数


        private void InitCaptureStoryborad()
        {
            _captureStoryborad = new Storyboard();
            _captureStoryborad.Duration = new Duration(TimeSpan.FromSeconds(1));//设置更新时间为1秒  
            _captureStoryborad.Completed += new EventHandler(s_Completed);
            LayoutRoot.Resources.Add("s", _captureStoryborad);
        }

        void s_Completed(object sender, EventArgs e)
        {
            //动作数
            _timeCount--;
            //当动作数不为0的时候需要进行下一个动作
            if (_timeCount != 0)
            {
                this.lab_time.Content = _timeCount.ToString();
                _captureStoryborad.Begin();
            }
            else
            {
                _captureSource.CaptureImageAsync();
                _timeCount = TIMESPAN_COUNT + 1;
            }
            
        }

        private void InitArgs()
        {
            _veryCount = 0;
            //_captureCount = TIMESPAN_ACTION + 1;
        }

        private void InitActornStoryborad()
        {
            _actionStoryborad = new Storyboard();
            _actionStoryborad.Duration = new Duration(TimeSpan.FromSeconds(1));
            _actionStoryborad.Completed += ActionStoryborad_Completed;
            LayoutRoot.Resources.Add("action", _actionStoryborad);
        }

        void ActionStoryborad_Completed(object sender, EventArgs e)
        {
            _currentActon = (AntiFaceAction)this.GetRandow();
            switch (_currentActon)
            {
                case AntiFaceAction.CLOSE_EYE:
                    this.lab_action.Content = "闭眼";
                    break;
                case AntiFaceAction.OPEN_EYE:
                    this.lab_action.Content = "睁大眼";
                    break;
                case AntiFaceAction.CLOSE_MOUTH:
                    this.lab_action.Content = "闭嘴";
                    break;
                case AntiFaceAction.OPEN_MOUNTH:
                    this.lab_action.Content = "张嘴";
                    break;
                case AntiFaceAction.LeffOrRight:
                    this.lab_action.Content = "扭头";
                    break;
                case AntiFaceAction.UpOrDown:
                    this.lab_action.Content = "点头";
                    break;
                default:
                    break;
            }
            _captureStoryborad.Begin();
        }



        private void StartCapture()
        {
            try
            {
                // Start capturing
                if (_captureSource.State != CaptureState.Started)
                {
                    // Create video brush and fill the WebcamVideo rectangle with it
                    var vidBrush = new VideoBrush();
                    vidBrush.Stretch = Stretch.Uniform;
                    vidBrush.SetSource(_captureSource);
                    WebcamVideo.Fill = vidBrush;


                    _captureImage = new ImageBrush();
                    rect_capture.Fill = _captureImage;
                    // Ask user for permission and start the capturing
                    if (CaptureDeviceConfiguration.RequestDeviceAccess())
                    {
                        _captureSource.Start();
                    }
                }
            }
            catch (InvalidOperationException ex)
            {
                //TextBoxInfo.Text = "Web Cam already started - if not, I can't find it...";
            }
            catch (Exception)
            {
                //TextBoxInfo.Text = "Could not start web cam, do you have one?";
            }
        }

        private void captureCompleted(object sender, CaptureImageCompletedEventArgs e)
        {

            try
            {
                var image = e.Result;
                var datas = image.ToByteArray();
                _captureImage.ImageSource = e.Result;
                if (datas != null)
                {
                    int height = image.PixelHeight;
                    int width = image.PixelWidth;
                    int bitsPerPixel = ((int)137224 & 0xff00) >> 8;
                    int bytesPerPixel = (bitsPerPixel + 7) / 8;
                    int stride = 4 * ((width * bytesPerPixel + 3) / 4);
                    //_socketConnection.SendData(detectedData);
                    _socketConnection.SendData(datas);
                    _socketConnection.SendData(BitConverter.GetBytes(width));
                    _socketConnection.SendData(BitConverter.GetBytes(height));
                    _socketConnection.SendData(BitConverter.GetBytes(stride));

                    _socketConnection.SendText(MSGENDSIGN);

                }
            }
            catch (Exception ex)
            {
 
            }
        }



        #endregion

        protected int GetRandow()
        {
            return _random.Next(1, 6);
        }

        private void Start_Click(object sender, RoutedEventArgs e)
        {
            StartCapture();
            InitArgs();
            _actionStoryborad.Begin();
            //_captureStoryborad.Begin();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            _captureSource.CaptureImageAsync();
        }


    }
}
